<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>语法_表单Ajax提交</title>
</head>

<body>
    <form id="myForm">
        <div>
            <!-- 用户名 -->
            <span>用户名：</span>
            <input type="text" name="username" id="username">
        </div>
        <!-- <div>
            <span>爱好：</span>
            <input type="text">
        </div>
        <div>
            <span>籍贯</span>
            <input type="text">
        </div> -->
        <div>
            <!-- 密码： -->
            <span>登录密码：</span>
            <input type="password" name="password" id="password">
        </div>
        <div>
            <!-- 提交按钮 给按钮补充id属性，方便dom获取-->
            <button id="submit">提交</button>
        </div>
    </form>

    <script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script>
    <script src="./lib/form-serialize.js"></script>
    <script>
        document.querySelector('#submit').addEventListener('click', (e) => {
            // 阻止默认行为
            e.preventDefault()

            // 获取表单元素的值
            // const username = document.querySelector('#username').value.trim()
            // const password = document.querySelector('#password').value.trim()
            // const password = document.querySelector('#password').value.trim()
            // console.log(username, password)
            // 有一个工具，可以批量获取全部的
            // 格式1
            // let result = serialize(document.querySelector('#myForm'))
            
            // 格式2. 得到一个对象
            let result = serialize(document.querySelector('#myForm'), { hash: true })
            console.log(result)

            axios({
                url: 'http://ajax-api.itheima.net/api/login',
                method: 'POST',
                data: result
                // data: {
                //     username: 'xx'
                // }
            }).then(res => {
                console.log(res)
            })

        })
    </script>
</body>

</html>